<?php

	session_start();
	if(!($_SESSION["username"])||($_SESSION["role"]!="TUT")){
		//not logged in or tutor
		header("location:index.php");
	}
	
	if (isset($_GET['file'])){
			$filename=$_GET['file'];
			
		// Get Document Path
		$strPath = realpath(basename(getenv($_SERVER["SCRIPT_NAME"]))); // C:/AppServ/www/myphp
		$OpenFile = "temp/".$filename;
		// Create Excel.Application
		$xlApp = new COM("Excel.Application");
		$xlBook = $xlApp->Workbooks->Open($strPath."/".$OpenFile);

		$xlSheet1 = $xlBook->Worksheets(1);

		//Insert into Database
		$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
		$objDB = mysql_select_db("Project 5.5");
		
		$sql="SELECT Class_ID FROM classes";
		$result=mysql_query($sql);
		
		$count=0;
		$currentIDs=null;
		
		while ($row = mysql_fetch_row($result)){
			$currentIDs[$count]=$row[0];			
			$count++;
		}

		$i=2;
		while($xlSheet1->Cells->Item($i,1) != ""){
			$SQL = "";
			if (in_array("".$xlSheet1->Cells->Item($i,1),$currentIDs)){
				$SQL .= "UPDATE classes SET ";
				$SQL .= "Class_ID='".$xlSheet1->Cells->Item($i,1)."', ";
				$SQL .= "Tutor='".$xlSheet1->Cells->Item($i,2)."', Location='".$xlSheet1->Cells->Item($i,3)."', ";
				$SQL .= "Size='".$xlSheet1->Cells->Item($i,4)."', Day='".$xlSheet1->Cells->Item($i,5)."', Time='".$xlSheet1->Cells->Item($i,6)."' ";
				$SQL .= "WHERE Class_ID='".$xlSheet1->Cells->Item($i,1)."'";
			} else {
				$SQL .= "INSERT INTO classes ";
				$SQL .= "(Class_ID,Tutor,Location,Size,Day,Time) ";
				$SQL .= "VALUES ";
				$SQL .= "('".$xlSheet1->Cells->Item($i,1)."','".$xlSheet1->Cells->Item($i,2)."' ";
				$SQL .= ",'".$xlSheet1->Cells->Item($i,3)."','".$xlSheet1->Cells->Item($i,4)."' ";
				$SQL .= ",'".$xlSheet1->Cells->Item($i,5)."','".$xlSheet1->Cells->Item($i,6)."')";
			}
			echo $SQL."<br/><br/>";
			mysql_query($SQL);
			$i++;
		}

		

		// Close & Quit
		mysql_close($objConnect);
		$xlApp->Application->Quit();
		$xlApp = null;
		$xlBook = null;
		$xlSheet1 = null;
		
		header("location:manageclasses.php?message=delete&file=".$_GET['file']);
	}
?>